package com.tally.framework.security.controller;

import com.tally.common.constant.Constants;
import com.tally.common.utils.CodeUtils;
import com.tally.common.utils.email.MailUtil;
import com.tally.framework.config.TallyConfig;
import com.tally.framework.web.AjaxResult;
import com.tally.project.system.user.domain.User;
import com.tally.project.system.user.service.IUserService;
import com.wf.captcha.ArithmeticCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * @Author qt
 * @Date 2021/3/25
 * @Description 主控制器
 */
@Api(tags = "认证")
@Controller
public class MainController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TallyConfig tallyConfig;

    @Autowired
    private MailUtil mailUtil;

    @Autowired
    private IUserService userService;

    public final static String SESSION_KEY_IMAGE_CODE = "SESSION_KEY_IMAGE_CODE";

    private Logger logger = LoggerFactory.getLogger(getClass());

    @ApiOperation("登录")
    @PostMapping("/user/login")
    @ResponseBody
    public void loginPage(String username, String password){ }


    @ApiOperation("验证码")
    @GetMapping("/captcha")
    @ResponseBody
    public AjaxResult createCode(HttpServletRequest request, HttpServletResponse response) {
        // 算术类型
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        // 几位数运算，默认是两位
        captcha.setLen(2);
        // 获取运算的结果
        String result = captcha.text();
        // 缓存到session
        request.getSession().setAttribute("code", result);

        return AjaxResult.success(captcha.toBase64());
    }

    /**
     *  邮件类型
     * @param str  邮件
     * @param flag 0.注册 1.找回密码、更改密码 2.邮件登陆 3.手机登陆
     * @return
     */
    @ApiOperation("验证码")
    @PutMapping("/captcha/{str}/{flag}")
    @ResponseBody
    public AjaxResult createCode(@PathVariable("str") String str, @PathVariable("flag") int flag) {
        String cache = Constants.getCacheCaptchaType(flag);
        // 找回或者更改需要验证数据库
        if (flag == 1){
            User user = userService.loadUserByUsername(str);
            if (user == null){
                return AjaxResult.error("用户不存在！");
            }else if (user.getEmail() == null || user.getEmail().isEmpty()){
                return AjaxResult.error("当前未绑定邮箱，请联系管理员进行操作！");
            }
            str = user.getEmail();
        }
        // 验证邮箱格式
        if (!CodeUtils.isEmail(str)){
            AjaxResult.error("邮箱格式有误！");
        }

        // 检查验证码是否已经存在
        if (redisTemplate.hasKey(cache + str)){
            return AjaxResult.success("验证码已发送，请注意查收！");
        }

        // 生成验证码
        Long code = CodeUtils.generateRandomCode(6);
        // 缓存Redis
        redisTemplate.boundValueOps(cache + str).set(code, tallyConfig.getCaptchaTimeOut(), TimeUnit.SECONDS);

        String format = String.format(MailUtil.mailText, tallyConfig.getSendMailMailer(), String.format(MailUtil.imMail, tallyConfig.getSendMailMailer()), tallyConfig.getSendMailMailer(), String.format(tallyConfig.getSendMailContent(), 6, code), "", tallyConfig.getSendMailMailer());
        mailUtil.sendMailMessage(tallyConfig.getSendMailMailer(), Arrays.asList(str), "您有一封来自" + tallyConfig.getSendMailMailer() + "的回执！", format);
        return AjaxResult.success("验证码已发送，请注意查收！");
    }


}
